<template>
    <div>
        <!-- 动态标题 -->
        <div class="table-header">
            <h2>{{ tableTitle }}</h2>
        </div>

        <!-- 信息栏 + 搜索框（同一行） -->
        <!-- 信息栏 + 搜索框（同一行） -->
        <div class="info-bar">

            <!-- 左：时间周期（保持原样） -->
            <div class="time-range" v-if="shar_date && end_date">
                时间周期: {{ shar_date }} 到 {{ end_date }}
            </div>

            <!-- 卡片区：支付/退款/退款率/千川消耗 -->
            <div class="stat-card-wrap">
                <div v-if="totalPaymentAmount !== null" class="stat-card">
                    <div class="stat-label">支付金额</div>
                    <div class="stat-value">{{ totalPaymentAmount }}</div>
                </div>

                <div v-if="totalRefundAmount !== null" class="stat-card">
                    <div class="stat-label">退款金额</div>
                    <div class="stat-value">{{ totalRefundAmount }}</div>
                </div>

                <div v-if="refundRatio !== null" class="stat-card">
                    <div class="stat-label">退款比例</div>
                    <div class="stat-value">{{ refundRatio }}%</div>
                </div>

                <div v-if="qianChuangCost !== null" class="stat-card">
                    <div class="stat-label">千川消耗</div>
                    <div class="stat-value">{{ qianChuangCost }}</div>
                </div>
            </div>

            <!-- 右：搜索框 -->
            <el-input
                    v-model="searchKeyword"
                    :placeholder="`搜索${tableFields[0] || ''}`"
                    clearable
                    class="search-input"
            >
                <template #prefix>
                    <el-icon><Search /></el-icon>
                </template>
            </el-input>
        </div>


        <!-- 表格 -->
        <el-table
                :data="filteredTableData"
                border
                size="medium"
                style="width: 100%; max-height: 600px; overflow-y: auto;"
                @row-click="handleRowClick"
        >
            <el-table-column
                    v-for="(field, index) in tableFields"
                    :key="index"
                    :prop="field"
                    :label="field"
                    sortable
            ></el-table-column>
        </el-table>


    </div>
</template>

<script setup>
    import {ref, computed, onMounted} from "vue";
    import {ElInput, ElIcon} from "element-plus";
    import {Search} from "@element-plus/icons-vue";

    import {useRoute} from 'vue-router'
    import dayjs from "dayjs";
    import api from "../../api";

    const route = useRoute()
    // 获取参数
    const section = route.query.section
    const type = route.query.name  //直播,商品卡  等
    const shop_name = route.query.shop_name
    const is_self = route.query.is_self  //self  coop  自营  合作
    // shar_end_date.value={"start":default_start_parm,"end":default_end_parm}
    const start_end_date = JSON.parse(route.query.start_end_date || '{}')
    const shar_date = start_end_date.start
    const end_date = start_end_date.end
    const date_or_month = start_end_date.type

    console.log("shar_date:", shar_date);
    console.log("end_date:", end_date);
    /* 示例数据 */
    // const tableData = ref([
    //     {抖音昵称: "双胞胎宝坊大飞", 支付金额: 8646.54, 支付比例: "14.11%", 退款金额: 4704.0, 退款比例: "51.54%"},
    //     {抖音昵称: "源源妈", 支付金额: 5833.08, 支付比例: "9.52%", 退款金额: 4622.77, 退款比例: "54.4%"},
    //     {抖音昵称: "雄妈", 支付金额: 4804.6, 支付比例: "7.52%", 退款金额: 2616.31, 退款比例: "79.25%"},
    //     {抖音昵称: "含任霖", 支付金额: 4578.44, 支付比例: "7.47%", 退款金额: 2004.0, 退款比例: "56.82%"},
    //     {抖音昵称: "妮包薇蔚", 支付金额: 3935.0, 支付比例: "6.42%", 退款金额: 2591.0, 退款比例: "65.84%"},
    // ]);
    const tableData = ref([]);
    /* 搜索关键字 */
    const searchKeyword = ref("");

    /* 动态表头 */
    const tableFields = ref([
        "渠道", "支付金额", "退款金额"
    ]);
    /* 模糊过滤 */
    const filteredTableData = computed(() => {
        if (!searchKeyword.value) return tableData.value;
        return tableData.value.filter((row) =>
            String(row[tableFields.value[0]]).includes(searchKeyword.value.trim())
        );
    });

    /* 动态标题 */
    const tableTitle = computed(() => {

        let res = shop_name

        if (is_self === "self") {
            res += " - 自营"
        } else {
            res += " - 合作"
        }
        res += " - " + type + " - 金额统计"

        return res;
    });


    /* 支付金额总和 */
    const totalPaymentAmount = computed(() => {
        const total = filteredTableData.value.reduce(
            (sum, item) => sum + (parseFloat(item["支付金额"]) || 0),
            0
        );
        return total.toFixed(2);
    });

    /* 退款金额总和 */
    const totalRefundAmount = computed(() => {
        const total = filteredTableData.value.reduce(
            (sum, item) => sum + (parseFloat(item["退款金额"]) || 0),
            0
        );
        return total.toFixed(2);
    });

    /* 退款比例 */
    const refundRatio = computed(() => {
        const pay = parseFloat(totalPaymentAmount.value);
        const refund = parseFloat(totalRefundAmount.value);
        return pay ? ((refund / pay) * 100).toFixed(2) : 0;
    });

    /* 千川消耗 */
    const qianChuangCost = computed(() => {
        const list = tableData.value;

        if (!Array.isArray(list) || list.length === 0) {
            return 0;
        }
        return list[0]?.["千川总消耗"] ?? 0;
    });


    const init_datas = async (date_or_month, star_parm, end_parm, shop_name, is_self, type) => {
        // {"date_or_month":"month", "star_parm":"2025-10",
        //     "end_parm":"2025-10","shop_name":"ROOKIE官方旗舰店", "is_self":"self", "type":"直播"}
        // 可在这里请求后端接口，更新趋势数据
        const res = await api.post("/douyin_project_analysis/shop_self_coop_detail", {
            date_or_month: date_or_month,
            star_parm: star_parm,
            end_parm: end_parm,
            shop_name: shop_name,
            is_self: is_self,
            type: type
        });
        // const keys = ["抖音昵称", "支付金额", "支付比例", "退款金额", "退款比例"];

        // tableData.value = res.data.data.map(item =>
        //     Object.fromEntries(
        //         Object.entries(item).filter(([key]) => tableFields.value.includes(key))
        //     )
        // );

        tableData.value = res.data.data;


        // cards.value = res.data.zong_kan_ban_datas;
        // zhengTiTrendData.value = res.data.zheng_ti_cheng_jiao_line_datas;
        // allShopDatas.value = res.data.shop_datas;
    }




    const handleRowClick = (row) => {

        const query = new URLSearchParams({
            date_or_month: date_or_month,
            start_date: shar_date,
            end_date: end_date,
            shop_name: shop_name,
            is_self:is_self,
            type: type,
            account_or_channel:row["渠道"]
        }).toString();

        const targetUrl = `/TableAndTandLine?${query}`;

        // ✅ 如果在钉钉环境
        if (window.dd) {
            try {
                dd.ready(() => {
                    dd.biz.util.openLink({url: targetUrl});
                });
            } catch (e) {
                // 如果 SDK 没初始化成功则降级处理
                window.location.href = targetUrl;
            }
        } else {
            // ✅ 普通浏览器，打开新标签
            window.open(targetUrl, "_blank");
        }
    };


    onMounted(() => {
        // 可在这里请求后端接口，更新趋势数据
        init_datas(date_or_month, shar_date, end_date, shop_name, is_self, type)

    })


</script>

<style scoped>
    /* 标题 */
    .table-header {
        text-align: center;
        font-size: 22px;
        font-weight: bold;
        margin-bottom: 16px;
    }

    /* ✅ 整体信息栏（左统计 + 右搜索） */
    .info-bar {
        display: flex;
        flex-direction: column; /* 卡片和输入框上下排列 */
        gap: 12px;
        margin-bottom: 18px;
    }
    /* 时间周期：保持原样 */
    .time-range {
        font-size: 20px;
        color: #000000;
        font-weight: 500;
    }




    /* 卡片区域：水平流式布局，自动换行 */
    .stat-card-wrap {
        display: flex;
        flex-wrap: wrap;
        gap: 12px;
    }

    /* 单个卡片 */
    .stat-card {
        flex: 1;
        min-width: 200px;
        padding: 12px 16px;
        border-radius: 8px;
        border: 1px solid #dbe3f0;
        background: #ffffff;
        box-shadow: 0 2px 6px rgba(0,0,0,0.05);
    }

    .stat-label {
        font-size: 14px;
        color: #6b7280;
        margin-bottom: 5px;
    }

    .stat-value {
        font-size: 20px;
        font-weight: 700;
        color: #111827;
        line-height: 1.2;
    }

    /* 搜索框靠右展示 */
    .search-input {
        width: 240px;
        align-self: flex-end;
    }

    /* 表格 */
    .el-table {
        max-height: 600px;
        overflow-y: auto;
    }

    /* 📱 移动端优化：上下排列 */
    @media (max-width: 768px) {
        .stat-card-wrap {
            flex-direction: column;
        }

        .search-input {
            width: 100%;
            align-self: stretch;
        }
    }
</style>
